14. Hide the Delete Menu Option For New Pets
Hide the Delete Menu Option for New Pets
You can’t delete it if it never existed
Another “quirk” of our current code is that when you’re in “insert mode” of the EditorActivity, you still see a Delete option in the menu. Since when you’re inserting a pet there isn’t a pet to delete, this is confusing.
So let’s fix this. We’ll need to remove the Delete menu option when in “insert mode”.
How To Choose What’s in the Menu While the App is Running
When you first open the activity, the onCreateOptionsMenu
method gets called. This inflates the menu with all menu items visible. To change this, what you need to do is as soon as you determine it’s a new pet (mPetContentUri is null), you should invalidate the options menu.
So in onCreate…
if (mCurrentPetUri == null) {
// This is a new pet, so change the app bar to say "Add a Pet"
setTitle(getString(R.string.editor_activity_title_new_pet));
// Invalidate the options menu, so the "Delete" menu option can be hidden.
// (It doesn't make sense to delete a pet that hasn't been created yet.)
invalidateOptionsMenu();
} else { //other stuff }
Then, in onPrepareOptionsMenu
will get called and you can modify the Menu object by hiding the delete menu option if it’s a new pet. The code for this is below:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// If this is a new pet, hide the "Delete" menu item.
if (mCurrentPetUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
Code Diff
To see the full set of changes made on this file, you can look at the code diff.
Commit 1.26 Hide delete menu option for new pets
Helpful links:
https://developer.android.com/guide/topics/ui/menus.html#options-menu
http://stackoverflow.com/questions/4199753/how-can-i-alter-a-menuitem-on-the-options-menu-on-android